<?php

namespace app\common\model;

use think\Model;

/**
 * 配置类
 * Class Config
 * @package app\common\model
 */
class Config extends Model
{
    protected $table = 'config';

    /**
     * 根据配置键获取配置值
     * @param $key
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($key)
    {
        $model = static::field('setting, is_json')
            ->where(['setting_key' => $key])
            ->find();
        $result = [];
        if ($model) {
            $result = ($model['is_json'] == 1) ? json_decode($model['setting'], true) : $model['setting'];
        }
        return $result;
    }

    /**
     * 返回积分可兑换的金额
     * @param $integral
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getReduceMoney($integral)
    {
        $reduceMoney = 0;
        $config = static::getOne('deduction');
        // 存在积分抵扣配置 并且 开启积分抵扣功能 并且积分大于可以抵扣的积分数
        if ($config && $config['isOn'] == true && $integral > $config['integral']) {
            if ($config['money'] > 0 && $config['integral'] > 0) {
                // 每1000可兑100
                $reduceMoney = (int)($integral / $config['integral']) * $config['money'];
                // 最多可兑换1000元
                if ($reduceMoney > $config['maxMoney']) {
                    $reduceMoney = $config['maxMoney'];
                }
            }
        }
        return $reduceMoney;
    }

    /**
     * 返回指定类型的积分配置
     * @param $type
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function integralGet($type)
    {
        $config = static::getOne('integral_get');
        $config = isset($config[$type]) ? $config[$type] : [];
        return $config;
    }

    /**
     * 指定类型积分获取，配置了当天最高拿积分，大于或等于当天最高，则不加积分
     * @param $oauthId
     * @param $type
     * @param $config
     * @return int
     */
    public static function integralMax($oauthId, $type, $config)
    {
        $integral = $config['integral'];
        // 存在最高积分配置
        if (isset($config['max'])) {
            // 指定用户指定获取积分类型当天总共得积分
            $dayNum = OauthIntegral::dayNum($oauthId, $type);
            if ($dayNum >= $config['max']) {
                $integral = 0;
            }
        }
        return $integral;
    }
}